package cn.t235.servlet;

import cn.t235.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/10/22.
 */
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    private UserService userService;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        userService = new UserService();
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String opt = req.getParameter("opt");
        if ("list".equals(opt)) {
            String realName = req.getParameter("realName");
            String[] roleIds = req.getParameterValues("roleIds");
            String pageNo = req.getParameter("pageNo");
            String pageSize = req.getParameter("pageSize");
            if (pageNo == null || "".equals(pageNo)) {
                pageNo = "1";
            }
            if (pageSize == null || "".equals(pageSize)) {
                pageSize = "2";
            }

            Integer[] roleIdArray = null;
            if(roleIds != null) {
                roleIdArray = new Integer[roleIds.length];
                for (int i = 0; i < roleIdArray.length; i++) {
                    roleIdArray[i] = Integer.valueOf(roleIds[i]);
                }
            }
            int pageNoInteger = Integer.parseInt(pageNo);
            int total = userService.getCount(realName, roleIdArray);
            int totalPageCount = total % Integer.parseInt(pageSize) == 0 ? total / Integer.parseInt(pageSize) : total / Integer.parseInt(pageSize) + 1;
            if (pageNoInteger < 1)  {pageNoInteger = 1;}
            if (pageNoInteger > totalPageCount) {pageNoInteger = totalPageCount;}
            req.setAttribute("realName", realName);
            req.setAttribute("pageNo", pageNoInteger);
            req.setAttribute("total", total);
            req.setAttribute("totalPageCount", totalPageCount);
            req.setAttribute("pageSize", pageSize);
            req.setAttribute("list", userService.get(realName, roleIdArray, pageNoInteger, Integer.parseInt(pageSize)));
        }
        req.getRequestDispatcher("/list.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
